package com.spring.forum.interceptor;

import com.spring.forum.constants.Constants;
import com.spring.forum.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取 token
        String token = request.getHeader(Constants.USER_TOKEN_HEADER);
        log.info("从header中获取token: {}" ,token);
        // 2.校验 token
        if (JwtUtils.parseToken(token) == null) {
            // 校验失败，打印错误信息
            // 给响应http状态设置为401
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
